﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate;
using NHibernate.Criterion;
using System.Diagnostics.Contracts;
using FoundationLib.Common;
using FoundationLib.Ifc;

namespace FoundationLib.Data.NHibernate
{
	/// <summary>
	/// Provides a default NHibernate page resolver implementation.
	/// </summary>
	/// <typeparam name="T">The type of the paged data records</typeparam>
	public class NHibernatePageResolver<T> : IPageResolver<T>
	{
		/// <summary>
		/// The NHibernate <see cref="IQueryOver{T, T}"/> query
		/// </summary>
		private IQueryOver<T, T> query;


		/// <summary>
		/// Creates a new <see cref="NHibernatePageResolver{T}"/>.
		/// </summary>
		/// <param name="query">The NHibernate criteria query</param>
		public NHibernatePageResolver(IQueryOver<T, T> query)
		{
			Contract.Requires(query != null);
			Contract.Ensures(this.query == query);
			this.query = query;
		}

		#region IPageResolver<T> Members

		/// <see cref="IPageResolver{T}.TotalItemCount"/>
		public int TotalItemCount
		{
			get
			{
				return query.RowCount();
			}
		}

		/// <see cref="IPageResolver{T}.GetPageItems(int, int)"/>
		public IEnumerable<T> GetPageItems(int pageIndex, int pageSize)
		{
			int skip = (pageIndex - 1) * pageSize;
			return query.Skip(skip).Take(pageSize).List<T>();
		}

		#endregion
	}
}
